package com.ruoyi.material.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.material.domain.constant.VIMSApiConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @program: MSS
 * @description: 获取VIMS_TOKEN
 * @author: cyw
 * @create: 2021-08-02 11:35
 **/
@Service
public class VIMSTokenService {
    private static  Logger logger = LoggerFactory.getLogger(VIMSTokenService.class);
    @Autowired
    private  RedisCache redisCache;


    private static String appKey = "77be010f7aa04abcb0888b2015aee0dc";
    private static String secret = "35e2748cda3a49dc88c7f4fbb0b49672";
    private static String VIMS_VIMS_API_ADDRESS = VIMSApiConstant.IP;
    private static String GET_TOKE_URL =   VIMS_VIMS_API_ADDRESS + "/openapi/v1/getToken";


    public  String getToken() throws Exception {
        redisCache.setCacheObject("token","d3bc5a1eba2bd7d549e8aac4ad17a96319a524eb90ad05c31628130529784",7, TimeUnit.DAYS);
        String token = redisCache.getCacheObject("token");

        if (token == null){
            String param = "appKey="+appKey+"&secret="+secret;
            logger.info("=====TokenUtil=====getToken()===请求地址 [{}]=======请求参数[{}]",GET_TOKE_URL,param);
            String resp =  HttpUtils.sendGet(GET_TOKE_URL,param);
            JSONObject paramsObj = JSONObject.parseObject(resp);
            token = paramsObj.getString("data");

            if (!StringUtils.isEmpty(token)){
                redisCache.setCacheObject("token",token,7, TimeUnit.DAYS);
            }
        }
        if (token == null){
            throw new Exception("获取token失败");
        }
        logger.info("=====TokenUtil=====getToken()===获得的Token=== {}",token);
        return token;
    }
    public  String getReToken() throws Exception {
            String param = "appKey="+appKey+"&secret="+secret;
            logger.info("=====TokenUtil=====getToken()===请求地址 [{}]=======请求参数[{}]",GET_TOKE_URL,param);
            String resp =  HttpUtils.sendGet(GET_TOKE_URL,param);
            JSONObject paramsObj = JSONObject.parseObject(resp);
            String token = paramsObj.getString("data");
            if (!StringUtils.isEmpty(token)){
                redisCache.setCacheObject("token",token,7, TimeUnit.DAYS);
            }

        if (token == null){
            throw new Exception("获取token失败");
        }
        logger.info("=====TokenUtil=====getToken()===获得的Token=== {}",token);
        return token;
    }
}
